package com.javaweb.bookstore.component;

import com.javaweb.bookstore.entity.Book;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
@Service

public class MemoryBookManager implements IBookManager {
    // 1. 私有静态实例
    private static MemoryBookManager instance;

    // 2. 私有构造函数
    private MemoryBookManager() {
        // 防止外部实例化
    }

    // 3. 公共静态获取实例方法
    public static synchronized MemoryBookManager getInstance() {
        if (instance == null) {
            instance = new MemoryBookManager();
        }
        return instance;
    }

    // 实例字段，非静态
    private List<Book> books = new CopyOnWriteArrayList<>();

    // 实例方法，非静态
    @Override
    public void createBook(Book b) {
        books.add(b);
    }

    @Override
    public void removeBook(String id) {
        Iterator<Book> iterator = books.iterator();
        while (iterator.hasNext()) {
            Book b = iterator.next();
            if (b.getId().equals(id)) {
                iterator.remove();
                break;
            }
        }
    }

    @Override
    public List<Book> getBooks(String key) {
        return new ArrayList<>(books); // 返回副本保护内部数据
    }

    @Override
    public Book getBook(String id) {
        return null;
    }
}